package com.webserver.core;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class ClientHandler implements Runnable{
    private Socket socket;

    public ClientHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            //解析请求行
            String line=readLine();
            System.out.println(line);

            String method;
            String uri;
            String protocol;

            String[] array=line.split("\\s");
            method=array[0];
            uri=array[1];
            protocol=array[2];
            //解析消息头
            System.out.println(method);
            System.out.println(uri);
            System.out.println(protocol);

            Map<String,String> headers=new HashMap<>();
            while (true){
                line=readLine();
                if (line.isEmpty()){
                    break;
                }
                System.out.println(line);
                array=line.split("\\s");
                headers.put(array[0],array[1]);
            }
            System.out.println(headers);


        } catch (IOException e) {
            e.printStackTrace();
        }

    }



    private String readLine() throws IOException {
        InputStream in=socket.getInputStream();
        char pre='a',cur='a';
        StringBuilder builder=new StringBuilder();
        int d;
        while ((d=in.read())!=-1){
            cur=(char)d;
            if (pre==13&&cur==10){
                break;
            }
            builder.append(cur);
            pre=cur;
        }
        return builder.toString().trim();
    }
}
